package com.xkdx.guangguang.fragment.user;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.HashMap;

import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.tencent.open.HttpStatusException;
import com.tencent.open.NetworkUnavailableException;
import com.tencent.tauth.Constants;
import com.tencent.tauth.IRequestListener;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboAuthListener;
import com.weibo.sdk.android.WeiboDialogError;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.api.UsersAPI;
import com.weibo.sdk.android.keep.AccessTokenKeeper;
import com.weibo.sdk.android.net.RequestListener;
import com.weibo.sdk.android.sso.SsoHandler;
import com.xkdx.caipiao.R;
import com.xkdx.guangguang.ManagerActivity;
import com.xkdx.guangguang.UpLoadHeadPhotoLoginActiivty;
import com.xkdx.guangguang.UserActivity;
import com.xkdx.guangguang.fragment.BaseFragment;
import com.xkdx.guangguang.fragment.my.setup.AttentionFragment;
import com.xkdx.guangguang.fragment.my.setup.PointFragment;
import com.xkdx.guangguang.fragment.user.UserBindQQModule.BindQQUser;
import com.xkdx.guangguang.fragment.user.UserBindSinaModule.BindUser;
import com.xkdx.guangguang.fragment.user.UserUnBindQQModule.UnBindQQUser;
import com.xkdx.guangguang.fragment.user.UserUnBindSinaModule.UnBindSinaInfo;
import com.xkdx.guangguang.fragment.user.UserUpdateBaseInfoModule.UserInfo;
import com.xkdx.guangguang.module.network.AbsModule;
import com.xkdx.guangguang.module.statics.IConstants;
import com.xkdx.guangguang.module.util.ErrorModule;
import com.xkdx.guangguang.presistence.uploadhead.UploadHeadAction;
import com.xkdx.guangguang.presistence.uploadhead.UploadHeadModule;
import com.xkdx.guangguang.presistence.uploadhead.UploadHeadPresistence;
import com.xkdx.guangguang.util.SharePrefenceUtil;

public class UserLoginSuccessFragment extends BaseFragment implements
		OnClickListener {

	private View view;
	private TextView sex, birthday, phone, email, nickname, modifypw;
	private Button exit, back;
	private ImageView im_sex, im_birthday, im_phone, im_email, head,
			iv_sinabind, iv_qqbind;
	private ImageButton point, attention;
	private RelativeLayout rl_sex, rl_birthday, rl_phone, rl_email;
	private UserSharePrefence user_sp;
	private ImageLoader imageLoader;
	private DisplayImageOptions options;
	private String headPath;
	public static Bitmap headBitmap = null;

	// 绑定新浪微博
	private String bindSinaToken;
	private String bindSinaUserID;
	private Weibo sinaWeibo;
	private SsoHandler mSsoHandler;
	private String uid;
	private long SinaWeiboUserID; // 新浪微博用户id
	private String UserNickName; // 用户昵称
	private String UserSex = "-1"; // 用户性别
	private static Oauth2AccessToken AccessToken;
	private String sinaWeiboToken;
	private String sinaWeiboExpireTime;

	private UserBindSinaAction bindSinaAction;
	private UserBindSinaModule bindSinaModule;
	private UserBindSinaPresenter bindSinaPresenter;
	private String bindSinaWeiboExpireTime;
	private BindUser user;
	private UnBindSinaInfo unbinduser;
	private UserUnBindSinaAction unbindSinaAction;
	private UserUnBindSinaModule unbindSinaModule;
	private UserUnBindSinaPresenter unbindSinaPresenter;
	private Tencent mbindTencent;
	private String QQExpireTime;
	private static final String SCOPE = "all";
	private String QQOpenID, QQToken, QQUserNickName, QQUserSex;
	private UserBindQQAction bindQQAction;
	private UserBindQQModule bindQQModule;
	private UserBindQQPresenter bindQQPresenter;
	private String bindQQToken;
	private String bindQQExpireTime;
	private String bindQQUserID;
	private BindQQUser bindQQUser;

	// 上传头像
	private UploadHeadAction uploadHeadAction;
	private UploadHeadModule uploadHeadModule;
	private UploadHeadPresistence uploadHeadPresistence;

	private UserUnBindQQAction unbindQQAction;
	private UserUnBindQQModule unbindQQModule;
	private UserUnBindQQPresenter unbindQQPresenter;
	private UnBindQQUser unbindQQuser;
	private AlertDialog alertDialog;
	private CheckBox cb1, cb2;
	private DatePicker datePicker;
	private EditText et_emai, et_phone;
	private int new_sex = 0;
	private String new_birthday = "", new_email = "", new_phone = "";

	private UserUpdateBaseInfoAction userBaseAction;
	private UserUpdateBaseInfoModule userBaseModule;
	private UserUpdateBaseInfoPresenter userBasePresenter;
	private UserInfo userInfo;
	private int index;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		user_sp = new UserSharePrefence(getActivity(), IConstants.SP_USER);
		imageLoader = ImageLoader.getInstance();
		headPath = Environment.getExternalStorageDirectory()
				+ "/GuangGuang/user/head.jpg";
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.uploadhead)
				.showImageForEmptyUri(R.drawable.uploadhead)
				.showImageOnFail(R.drawable.uploadhead)
				.resetViewBeforeLoading().cacheOnDisc()
				.imageScaleType(ImageScaleType.EXACTLY)
				.bitmapConfig(Bitmap.Config.RGB_565).build();
		File file = new File(headPath);
		if (!file.exists()) {
			SaveHeadImageAsy saveHeadImageAsy = new SaveHeadImageAsy();
			saveHeadImageAsy.execute();
		}

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.user_login_success, container, false);
		findViews();
		setOnClick();
		return view;
	}

	private void findViews() {
		IConstants.hideInputMethodAways(getActivity(), view);
		sex = (TextView) view.findViewById(R.id.sex);
		birthday = (TextView) view.findViewById(R.id.birthday);
		phone = (TextView) view.findViewById(R.id.phone);
		email = (TextView) view.findViewById(R.id.email);
		nickname = (TextView) view.findViewById(R.id.user_sucesslogin_nickname);
		exit = (Button) view.findViewById(R.id.exit);
		im_sex = (ImageView) view.findViewById(R.id.login_seximage);
		im_birthday = (ImageView) view.findViewById(R.id.login_birthdayimage);
		im_phone = (ImageView) view.findViewById(R.id.head3);
		im_email = (ImageView) view.findViewById(R.id.head4);
		head = (ImageView) view.findViewById(R.id.login_sucess_headimage);
		iv_sinabind = (ImageView) view
				.findViewById(R.id.login_sucess_sina_bind);
		iv_qqbind = (ImageView) view
				.findViewById(R.id.login_sucess_stencent_bind);

		point = (ImageButton) view.findViewById(R.id.point_btn);
		attention = (ImageButton) view.findViewById(R.id.attention_btn);
		rl_sex = (RelativeLayout) view.findViewById(R.id.rl_sex);
		rl_birthday = (RelativeLayout) view.findViewById(R.id.rl_birthday);
		rl_phone = (RelativeLayout) view.findViewById(R.id.rl_phone);
		rl_email = (RelativeLayout) view.findViewById(R.id.rl_email);
		modifypw = (TextView) view.findViewById(R.id.tv_modifypw);
		back = (Button) view.findViewById(R.id.login_success_back);

		rl_sex.setOnClickListener(this);
		rl_birthday.setOnClickListener(this);
		rl_phone.setOnClickListener(this);
		rl_email.setOnClickListener(this);
		modifypw.setOnClickListener(this);
		nickname.setOnClickListener(this);

		exit.setOnClickListener(this);
		point.setOnClickListener(this);
		attention.setOnClickListener(this);
		sex.setOnClickListener(this);
		birthday.setOnClickListener(this);
		phone.setOnClickListener(this);
		email.setOnClickListener(this);
		head.setOnClickListener(this);
		iv_sinabind.setOnClickListener(this);
		iv_qqbind.setOnClickListener(this);
		back.setOnClickListener(this);
		setInitValue();

	}

	/**
	 * 页面填充数据
	 */
	private void setInitValue() {

		if ("0".equals(user_sp.getUserSex())) {
			sex.setText("男");
			im_sex.setImageResource(R.drawable.sex);
		} else if ("1".equals(user_sp.getUserSex())) {
			sex.setText("女");
		} else {
			sex.setText("未知");
			im_sex.setImageResource(R.drawable.sex_null);
		}

		if (!user_sp.getUserBirthday().equals("")) {
			if (user_sp.getUserBirthday() != null) {
				birthday.setText(user_sp.getUserBirthday());
			}
			im_birthday.setImageResource(R.drawable.birthday);
		} else {
			im_birthday.setImageResource(R.drawable.birthday_null);
		}

		if (!user_sp.getUserEmail().equals("")) {
			email.setText(user_sp.getUserEmail());
			im_email.setImageResource(R.drawable.email);
		} else {
			im_email.setImageResource(R.drawable.email_null);
		}
		if (!user_sp.getUserMobilePhone().equals("")) {
			phone.setText(user_sp.getUserMobilePhone());
			im_phone.setImageResource(R.drawable.phone);
		} else {
			im_phone.setImageResource(R.drawable.phone_null);
		}

		nickname.setText(("".equals(user_sp.getUserNickName()) ? "昵称" : user_sp
				.getUserNickName()));
		bindSinaToken = user_sp.getSinaWeiboToken();
		bindSinaUserID = user_sp.getUserID();

		iv_sinabind.setImageResource((!"".equals(bindSinaToken) && (!""
				.equals(bindSinaUserID))) ? R.drawable.sina_bind
				: R.drawable.sina_unbind);

		// 增加腾讯qq绑定信息
		bindQQToken = user_sp.getQQToken();
		bindQQUserID = user_sp.getUserID();

		iv_qqbind.setImageResource((!"".equals(bindQQToken) && (!""
				.equals(bindQQUserID))) ? R.drawable.qq_bind
				: R.drawable.qq_unbind);
		imageLoader.displayImage(user_sp.getUserPictureUrl(), head, options);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.tv_modifypw: // 修改密码
			FragmentTransaction ft_modifypwd = getFragmentManager()
					.beginTransaction();
			UserModifypwFragment userModifypwFragment = new UserModifypwFragment();
			ft_modifypwd.replace(R.id.fragment, userModifypwFragment,
					"userModifypwFragment");
			ft_modifypwd.addToBackStack(null);
			ft_modifypwd.commit();
			break;

		case R.id.user_sucesslogin_nickname:// 修改昵称
			FragmentTransaction ft4 = getFragmentManager().beginTransaction();
			UserModifyNickNameFragment modifyNickFragment = new UserModifyNickNameFragment();
			ft4.replace(R.id.fragment, modifyNickFragment,
					"userModifyNickNameFragment");
			ft4.addToBackStack(null);
			ft4.commit();
			break;

		case R.id.login_sucess_sina_bind:
			bindOrunBindSina(); // 绑定新浪微博或解绑
			break;
		case R.id.login_sucess_stencent_bind: // 绑定腾讯qq
			bindOrunBindQQ();
			break;

		case R.id.login_success_back:
			if (headBitmap != null && !headBitmap.isRecycled()) {
				headBitmap.recycle();
				headBitmap = null;
			}

			int k = getFragmentManager().getBackStackEntryCount();
			for (int i = 0; i < k - 1; i++) {
				getFragmentManager().popBackStack();
			}
			break;
		case R.id.exit: // 退出登陆，清除所有用户信息

			dataLoadDialog.setMessage("正处理用户数据,请等待...");
			dataLoadDialog.setCancelable(true);
			dataLoadDialog.show();
			IConstants.IsDisEnable = false;
			user_sp.clear();

			File headfile = new File(headPath);
			if (headfile.exists()) {
				headfile.delete();
			}
			if (getActivity() != null) {
				Tencent mTencent = ((UserActivity) getActivity()).getTencent();
				if (mTencent != null) {
					mTencent.logout(getActivity());
				}
				if (mbindTencent != null) {
					mbindTencent.logout(getActivity());
				}
				AccessTokenKeeper.clear(getActivity());
			}
			if (dataLoadDialog != null && dataLoadDialog.isShowing()) {
				dataLoadDialog.dismiss();
			}
			FragmentManager fm = getFragmentManager();
			fm.popBackStack();
			FragmentTransaction ft = getFragmentManager().beginTransaction();
			UserLoginFragment myLoginFragment = new UserLoginFragment();
			ft.replace(R.id.fragment, myLoginFragment, "userLoginFragment");
			ft.addToBackStack(null);
			ft.commit();

			break;
		case R.id.login_sucess_headimage:
			Intent intent = new Intent(getActivity(),
					UpLoadHeadPhotoLoginActiivty.class);
			startActivity(intent);
			break;

		case R.id.point_btn: // 我的积分
			FragmentTransaction ft1 = getFragmentManager().beginTransaction();
			PointFragment pointFragment = new PointFragment();
			ft1.replace(R.id.fragment, pointFragment);
			ft1.addToBackStack(null);
			ft1.commit();
			break;
		case R.id.attention_btn: // 我的关注
			FragmentTransaction ft2 = getFragmentManager().beginTransaction();
			AttentionFragment attentionFragment = new AttentionFragment();
			ft2.replace(R.id.fragment, attentionFragment);
			ft2.addToBackStack(null);
			ft2.commit();
			break;

		case R.id.rl_sex:
			index = 1;
			alertDialog = getDialog("请选择性别:", 1);
			alertDialog.show();
			break;
		case R.id.rl_birthday:
			index = 2;
			alertDialog = getDialog("请选择生日:", 2);
			alertDialog.show();
			break;
		case R.id.rl_email:
			if (!IConstants.IsDisEnable) {
				index = 3;
				alertDialog = getDialog("请输入邮箱地址:", 3);
				alertDialog.show();
			}
			break;
		case R.id.rl_phone:
			if (!IConstants.IsDisEnable) {
				index = 4;
				alertDialog = getDialog("请输入手机号:", 4);
				alertDialog.show();
			}
			break;
		case R.id.checkBox1:
			if (cb1.isChecked()) {
				cb2.setChecked(false);
				new_sex = 0;
			} else {
				cb2.setChecked(true);
				new_sex = 1;
			}

			break;
		case R.id.checkBox2:
			if (cb2.isChecked()) {
				cb1.setChecked(false);
				new_sex = 1;
			} else {
				cb1.setChecked(true);
				new_sex = 0;
			}
			break;

		default:
			break;
		}
	}

	private AlertDialog getDialog(String title, final int index) {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		View view;
		builder.setTitle(title);
		switch (index) {
		case 1:
			view = LayoutInflater.from(getActivity()).inflate(
					R.layout.update_user_info_sex, null);
			cb1 = (CheckBox) view.findViewById(R.id.checkBox1);
			cb2 = (CheckBox) view.findViewById(R.id.checkBox2);
			cb1.setOnClickListener(this);
			cb2.setOnClickListener(this);
			builder.setView(view);
			break;
		case 2:
			view = LayoutInflater.from(getActivity()).inflate(
					R.layout.update_user_info_datapicker, null);
			datePicker = (DatePicker) view.findViewById(R.id.datePicker1);
			builder.setView(view);
			break;
		case 3:
			view = LayoutInflater.from(getActivity()).inflate(
					R.layout.update_user_info_dialog_email, null);
			et_emai = (EditText) view.findViewById(R.id.update_user_info_et);
			builder.setView(view);
			break;
		case 4:
			view = LayoutInflater.from(getActivity()).inflate(
					R.layout.update_user_info_dialog_email, null);
			et_phone = (EditText) view.findViewById(R.id.update_user_info_et);
			builder.setView(view);
			break;
		default:
			break;
		}

		userBasePresenter = new UserUpdateBaseInfoPresenter(this);
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (index) {
				case 1:
					userBaseAction = new UserUpdateBaseInfoAction(user_sp
							.getUserID(), new_sex + "",
							user_sp.getLoginToken(), 1);
					userBaseModule = new UserUpdateBaseInfoModule(
							getActivity(), 1);
					break;
				case 2:
					new_birthday = datePicker.getYear() + "-"
							+ (datePicker.getMonth() + 1) + "-"
							+ datePicker.getDayOfMonth();
					userBaseAction = new UserUpdateBaseInfoAction(user_sp
							.getUserID(), new_birthday,
							user_sp.getLoginToken(), 2);
					userBaseModule = new UserUpdateBaseInfoModule(
							getActivity(), 2);
					break;
				case 3:

					new_email = et_emai.getText().toString();
					userBaseAction = new UserUpdateBaseInfoAction(user_sp
							.getUserID(), new_email, user_sp.getLoginToken(), 3);
					userBaseModule = new UserUpdateBaseInfoModule(
							getActivity(), 3);

					break;

				case 4:

					new_phone = et_phone.getText().toString();
					userBaseAction = new UserUpdateBaseInfoAction(user_sp
							.getUserID(), new_phone, user_sp.getLoginToken(), 4);
					userBaseModule = new UserUpdateBaseInfoModule(
							getActivity(), 4);

					break;
				default:
					break;
				}

				((ManagerActivity) getActivity())
						.addCurrentTask(userBasePresenter);
				userBasePresenter.setActitons(userBaseAction);
				userBasePresenter.setModule(userBaseModule);
				userBasePresenter.execute();
				dataLoadDialog.setOnCancelListener(new OnCancelListener() {

					@Override
					public void onCancel(DialogInterface dialog) {
						if (userBasePresenter != null) {
							userBasePresenter.cancel(true);
						}
						getFragmentManager().popBackStack();

					}
				});
				dataLoadDialog.show();
			}

		}

		);
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				alertDialog.cancel();
			}
		});

		return builder.create();
	}

	/**
	 * qq绑定与解绑
	 */
	private void bindOrunBindQQ() {
		if (!"".equals(bindQQToken) && (!"".equals(bindQQUserID))) {
			UnbindQQ();
		} else {
			BindQQ();
		}
	}

	/**
	 * 解除绑定qq
	 */
	private void UnbindQQ() {
		unbindQQPresenter = new UserUnBindQQPresenter(this);
		// 创建对话框
		AlertDialog.Builder ab = new AlertDialog.Builder(getActivity());
		ab.setTitle("提示");
		ab.setMessage("确定要解绑腾讯qq账号吗?");
		ab.setPositiveButton("确认", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				UnBindQQ(dialog);
				dialog.dismiss();
			}
		});

		ab.setNegativeButton("取消", null);
		// 显示对话框
		ab.show();
	}

	protected void UnBindQQ(DialogInterface dialog) {

		unbindQQAction = new UserUnBindQQAction(user_sp.getUserID(),
				user_sp.getLoginToken(), user_sp.getQQOpenID());
		unbindQQModule = new UserUnBindQQModule(getActivity());
		((ManagerActivity) getActivity()).addCurrentTask(unbindQQPresenter);
		unbindQQPresenter.setActitons(unbindQQAction);
		unbindQQPresenter.setModule(unbindQQModule);
		unbindQQPresenter.execute();
	}

	/**
	 * 绑定qq
	 */
	private void BindQQ() {
		IConstants.LoginWhich = 5;
		bindQQPresenter = new UserBindQQPresenter(this);
		mbindTencent = ((UserActivity) getActivity()).getbindTencent();
		if (!mbindTencent.isSessionValid()) {
			IUiListener listener = new BaseUiListener() {

				@Override
				protected void doComplete(JSONObject values) {
					// Log.i(TAG, "isValid-->" + isValid());
					if (isValid()) {
						// StartLoading();
						try {
							QQExpireTime = values.getString("expires_in");
						} catch (JSONException e) {
							e.printStackTrace();
						}
						mbindTencent
								.requestAsync(Constants.GRAPH_SIMPLE_USER_INFO,
										null, Constants.HTTP_GET,
										new BaseApiListener(), null);
					}
				}
			};

			mbindTencent.login(getActivity(), SCOPE, listener);
		} else {
			mbindTencent.logout(getActivity());
		}
	}

	/**
	 * tencent 的监听认证接口
	 * 
	 * @author Administrator
	 * 
	 */
	private class BaseApiListener implements IRequestListener {

		@Override
		public void onComplete(final JSONObject response, Object state) {
			showResult(response.toString());
			doComplete(response, state);
		}

		protected void doComplete(JSONObject response, Object state) {
		}

		@Override
		public void onIOException(final IOException e, Object state) {

		}

		@Override
		public void onMalformedURLException(final MalformedURLException e,
				Object state) {

		}

		@Override
		public void onJSONException(final JSONException e, Object state) {

		}

		@Override
		public void onConnectTimeoutException(ConnectTimeoutException arg0,
				Object arg1) {

		}

		@Override
		public void onSocketTimeoutException(SocketTimeoutException arg0,
				Object arg1) {

		}

		@Override
		public void onUnknowException(Exception arg0, Object arg1) {

		}

		@Override
		public void onHttpStatusException(HttpStatusException arg0, Object arg1) {

		}

		@Override
		public void onNetworkUnavailableException(
				NetworkUnavailableException arg0, Object arg1) {
		}
	}

	private void showResult(final String msg) {

		new Thread() {
			@Override
			public void run() {
				JSONObject userinfoObject;
				try {
					userinfoObject = new JSONObject(msg);

					QQUserNickName = userinfoObject.getString("nickname");
					QQUserSex = (String) userinfoObject.getString("gender");
					if ("男".equals(UserSex)) {
						QQUserSex = "0";
					} else if ("女".equals(UserSex)) {
						QQUserSex = "1";
					} else {
						QQUserSex = "-1";
					}

					h.sendEmptyMessage(1);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	private Handler h = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (getActivity() == null) {
				return;
			}

			if (msg.what == 1) { // 处理腾讯登陆
				bindQQAction = new UserBindQQAction(user_sp.getUserID(),
						user_sp.getUserLoginToken(), String.valueOf(QQOpenID),
						UserNickName, UserSex, QQToken, QQExpireTime);
				bindQQModule = new UserBindQQModule(getActivity());
				((ManagerActivity) getActivity())
						.addCurrentTask(bindQQPresenter);
				bindQQPresenter.setActitons(bindQQAction);
				bindQQPresenter.setModule(bindQQModule);
				bindQQPresenter.execute();
			}
		}
	};

	private boolean isValid() {

		boolean ready = (mbindTencent.isSessionValid())
				&& (mbindTencent.getOpenId() != null);
		return ready;
	}

	// 腾讯qq登录时的事件监听
	private class BaseUiListener implements IUiListener {

		@Override
		public void onComplete(JSONObject response) {
			QQOpenID = mbindTencent.getOpenId();
			QQToken = mbindTencent.getAccessToken();

			// Log.i(TAG, "QQOpenID:" + QQOpenID);
			doComplete(response);
		}

		protected void doComplete(JSONObject values) {
			// Log.i(TAG, "QQOpenID:" + values.toString());
		}

		@Override
		public void onError(UiError e) {
			// Log.i(TAG, e.errorDetail);

		}

		@Override
		public void onCancel() {
			// Log.i(TAG, "onCancel-->");
		}
	}

	/**
	 * 点击新浪图标进行绑定与解绑
	 */
	private void bindOrunBindSina() {
		if (!"".equals(bindSinaToken) && (!"".equals(bindSinaUserID))) {
			unbindSinaPresenter = new UserUnBindSinaPresenter(this);
			UnbindSina();// 解绑新浪微博

		} else {
			bindSinaPresenter = new UserBindSinaPresenter(this);
			BindSina(); // 绑定新浪微博
		}
	}

	// 绑定新浪微博
	private void BindSina() {
		IConstants.LoginWhich = 4;
		sinaWeibo = Weibo.getInstance(IConstants.CONSUMER_KEY,
				IConstants.REDIRECT_URL);
		try {
			Class sso = Class.forName("com.weibo.sdk.android.sso.SsoHandler");
			mSsoHandler = new SsoHandler(getActivity(), sinaWeibo);
			mSsoHandler.authorize(new AuthDialogListener());

		} catch (ClassNotFoundException e) {
			sinaWeibo.authorize(getActivity(), new AuthDialogListener());
		}
	}

	public SsoHandler GetBindSsoHandler() {
		return mSsoHandler;
	}

	/**
	 * 处理新浪绑定
	 */
	class AuthDialogListener implements WeiboAuthListener {

		@Override
		public void onComplete(Bundle values) {

			String token = values.getString("access_token");
			String expires_in = values.getString("expires_in");
			uid = values.getString("uid");
			sinaWeiboToken = token; // 新浪微博token
			sinaWeiboExpireTime = expires_in;

			UserLoginSuccessFragment.AccessToken = new Oauth2AccessToken(token,
					expires_in);

			if (UserLoginSuccessFragment.AccessToken.isSessionValid()) {

				try {
					Class sso = Class
							.forName("com.weibo.sdk.android.api.WeiboAPI");// 如果支持weiboapi的话，显示api功能演示入口按钮
				} catch (ClassNotFoundException e) {
				}
				AccessTokenKeeper.keepAccessToken(getActivity(),
						UserLoginSuccessFragment.AccessToken);

				if (Long.parseLong(uid) > 0) {
					SinaWeiboUserID = Long.parseLong(uid);
					UsersAPI user = new UsersAPI(AccessToken);
					user.show(SinaWeiboUserID, new RequestListener() {
						@Override
						public void onIOException(IOException e) {
						}

						@Override
						public void onError(WeiboException e) {
						}

						@Override
						public void onComplete(String response) {

							JSONObject userObject;
							try {
								userObject = new JSONObject(response);
								UserNickName = userObject
										.getString("screen_name");
								UserSex = (String) userObject
										.getString("gender");
								if ("m".equals(UserSex)) {
									UserSex = "0";
								} else if ("f".equals(UserSex)) {
									UserSex = "1";
								} else {
									UserSex = "-1";
								}

							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					});

					bindSinaAction = new UserBindSinaAction(
							user_sp.getUserID(), user_sp.getUserLoginToken(),
							String.valueOf(SinaWeiboUserID), UserNickName,
							UserSex, sinaWeiboToken, sinaWeiboExpireTime);
					bindSinaModule = new UserBindSinaModule(getActivity());
					((ManagerActivity) getActivity())
							.addCurrentTask(bindSinaPresenter);
					bindSinaPresenter.setActitons(bindSinaAction);
					bindSinaPresenter.setModule(bindSinaModule);
					bindSinaPresenter.execute();
				}

			}
		}

		@Override
		public void onError(WeiboDialogError e) {

		}

		@Override
		public void onCancel() {

		}

		@Override
		public void onWeiboException(WeiboException e) {

		}

	}

	// 解除绑定新浪微博
	private void UnbindSina() {
		// 创建对话框
		AlertDialog.Builder ab = new AlertDialog.Builder(getActivity());
		ab.setTitle("提示");
		ab.setMessage("确定要解绑新浪微博账号吗?");
		ab.setPositiveButton("确认", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				UnBindSina(dialog);
				dialog.dismiss();
			}
		});

		ab.setNegativeButton("取消", null);
		// 显示对话框
		ab.show();
	}

	protected void UnBindSina(DialogInterface dialog) {
		unbindSinaAction = new UserUnBindSinaAction(user_sp.getUserID(),
				user_sp.getLoginToken(), user_sp.getSinaWeiboUserID());
		unbindSinaModule = new UserUnBindSinaModule(getActivity());
		((ManagerActivity) getActivity()).addCurrentTask(unbindSinaPresenter);
		unbindSinaPresenter.setActitons(unbindSinaAction);
		unbindSinaPresenter.setModule(unbindSinaModule);
		unbindSinaPresenter.execute();
	}

	/**
	 * 由于涉及上传头像，绑定新浪等操作需要刷新页面，故头像变动在onResume里执行
	 */
	@Override
	public void onResume() {
		super.onResume();
		if (headBitmap != null) {
			SharePrefenceUtil su = new SharePrefenceUtil(getActivity(),
					IConstants.SP_USER);
			uploadHeadAction = new UploadHeadAction(su.getUserID(),
					su.getUserLoginToken());
			uploadHeadModule = new UploadHeadModule();
			uploadHeadPresistence = new UploadHeadPresistence(this);
			uploadHeadPresistence.setActitons(uploadHeadAction);
			uploadHeadPresistence.setModule(uploadHeadModule);
			uploadHeadPresistence.execute();
		}

		// setInitValue();
		bindSinaToken = user_sp.getSinaWeiboToken();
		bindSinaWeiboExpireTime = user_sp.getSinaWeiboExpireTime();
		bindSinaUserID = user_sp.getUserID();
		iv_sinabind.setImageResource((!"".equals(bindSinaToken) && (!""
				.equals(bindSinaUserID))) ? R.drawable.sina_bind
				: R.drawable.sina_unbind);

		// 增加腾讯qq绑定信息
		bindQQToken = user_sp.getQQToken();
		bindQQUserID = user_sp.getUserID();

		iv_qqbind.setImageResource((!"".equals(bindQQToken) && (!""
				.equals(bindQQUserID))) ? R.drawable.qq_bind
				: R.drawable.qq_unbind);

	}

	public void showLoaded(HashMap<String, AbsModule> msg) {

		if (msg.containsKey("0")) {
			user = ((UserBindSinaModule) msg.get("0")).bindUser;
			if (user != null && user.getStatus() != null
					&& user.getStatus().equals("Success")) {

				Toast.makeText(getActivity(), "新浪微博绑定成功", Toast.LENGTH_SHORT)
						.show();
				iv_sinabind.setImageResource(R.drawable.sina_bind);
				bindSinaToken = user_sp.getSinaWeiboToken();
				bindSinaWeiboExpireTime = user_sp.getSinaWeiboExpireTime();
				bindSinaUserID = user_sp.getUserID();

			} else {
				Toast.makeText(getActivity(), user.getMessage(),
						Toast.LENGTH_SHORT).show();
			}
		} else {
			Toast.makeText(getActivity(),
					((ErrorModule) msg.get("1")).errorMessage,
					Toast.LENGTH_SHORT).show();
		}

	}

	public void showQQLoaded(HashMap<String, AbsModule> msg) {

		if (msg.containsKey("0")) {
			bindQQUser = ((UserBindQQModule) msg.get("0")).bindQQUser;
			if (bindQQUser != null && bindQQUser.getStatus() != null
					&& bindQQUser.getStatus().equals("Success")) {

				Toast.makeText(getActivity(), "新浪微博绑定成功", Toast.LENGTH_SHORT)
						.show();
				iv_qqbind.setImageResource(R.drawable.qq_bind);
				bindQQToken = user_sp.getQQToken();
				bindQQExpireTime = user_sp.getQQExpireTime();
				bindQQUserID = user_sp.getUserID();

			} else {
				Toast.makeText(getActivity(), bindQQUser.getMessage(),
						Toast.LENGTH_SHORT).show();
			}
		} else {
			Toast.makeText(getActivity(),
					((ErrorModule) msg.get("1")).errorMessage,
					Toast.LENGTH_SHORT).show();
		}

	}

	/**
	 * 新浪解除绑定成功
	 */
	public void showUnBindSinaLoaded(HashMap<String, AbsModule> msg) {

		if (msg.containsKey("0")) {
			unbinduser = ((UserUnBindSinaModule) msg.get("0")).unbindUser;
			if (unbinduser != null && unbinduser.getStatus() != null
					&& unbinduser.getStatus().equals("Success")) {

				Toast.makeText(getActivity(), "新浪微博解除绑定成功", Toast.LENGTH_SHORT)
						.show();
				iv_sinabind.setImageResource(R.drawable.sina_unbind);
				bindSinaToken = user_sp.getSinaWeiboToken();
				bindSinaWeiboExpireTime = user_sp.getSinaWeiboExpireTime();
				bindSinaUserID = user_sp.getUserID();

			} else {

				Toast.makeText(getActivity(), unbinduser.getMessage(),
						Toast.LENGTH_SHORT).show();
			}
		} else {
			Toast.makeText(getActivity(),
					((ErrorModule) msg.get("1")).errorMessage,
					Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * qq解除绑定成功
	 */
	public void showUnBindQQLoaded(HashMap<String, AbsModule> msg) {

		if (msg.containsKey("0")) {
			unbindQQuser = ((UserUnBindQQModule) msg.get("0")).unbindUser;
			if (unbindQQuser != null && unbindQQuser.getStatus() != null
					&& unbindQQuser.getStatus().equals("Success")) {

				Toast.makeText(getActivity(), "qq解除绑定成功", Toast.LENGTH_SHORT)
						.show();
				iv_qqbind.setImageResource(R.drawable.qq_unbind);
				bindQQToken = user_sp.getQQOpenID();
				bindQQExpireTime = user_sp.getQQExpireTime();
				bindQQUserID = user_sp.getUserID();

			} else {
				Toast.makeText(getActivity(), unbindQQuser.getMessage(),
						Toast.LENGTH_SHORT).show();
			}
		} else {
			Toast.makeText(getActivity(),
					((ErrorModule) msg.get("1")).errorMessage,
					Toast.LENGTH_SHORT).show();
		}

	}

	public void showUpdateBaseInfo(HashMap<String, AbsModule> map) {
		dataLoadDialog.dismiss();
		alertDialog.cancel();
		if (map.containsKey("0")) {
			userInfo = ((UserUpdateBaseInfoModule) map.get("0")).userInfo;
			if (userInfo != null && userInfo.getStatus() != null
					&& userInfo.getStatus().equals("Success")) {
				Toast.makeText(getActivity(), "信息修改成功...", Toast.LENGTH_SHORT)
						.show();
				if (index == 1) {
					if (new_sex == 1) {
						sex.setText("女");
						user_sp.setUserSex("1");

					} else if (new_sex == 0) {
						sex.setText("男");
						user_sp.setUserSex("0");
					} else {
						sex.setText("未知");
						user_sp.setUserSex("-1");
					}
				}
				// sex.setText(user_sp.getUserSex());
				else if (index == 2) {
					birthday.setText(new_birthday);
					user_sp.setUserBirthday(new_birthday);
				} else if (index == 3) {
					email.setText(userInfo.getEmail());
				} else {
					phone.setText(userInfo.getMobilePhone());
				}

			} else {
				Toast.makeText(getActivity(), userInfo.getMessage(), 0).show();
			}

		} else {
			Toast.makeText(getActivity(),
					((ErrorModule) map.get("1")).errorMessage,
					Toast.LENGTH_SHORT).show();
		}

	}

	@Override
	public void showClick(HashMap<String, AbsModule> map) {
		dataLoadDialog.dismiss();
		if (map.containsKey("0")) {
			if (uploadHeadModule.isUploadSuccess) {
				reSetUserHead();
				Toast.makeText(getActivity(), "上传成功", Toast.LENGTH_SHORT)
						.show();
			} else {
				Toast.makeText(getActivity(), "上传失败", Toast.LENGTH_SHORT)
						.show();
			}

		} else {
			Toast.makeText(getActivity(),
					((ErrorModule) map.get("1")).errorMessage,
					Toast.LENGTH_SHORT).show();
		}
		if (headBitmap != null) {
			headBitmap.recycle();
			headBitmap = null;
		}

	}

	@Override
	public void showLoadMore(HashMap<String, AbsModule> map) {
		// TODO Auto-generated method stub

	}

	@Override
	public void showLoading() {
		// TODO Auto-generated method stub

	}

	@Override
	public void findView() {
		// TODO Auto-generated method stub

	}

	@Override
	public void setOnClick() {
		// TODO Auto-generated method stub

	}

	private void reSetUserHead() {
		SharePrefenceUtil su = new SharePrefenceUtil(getActivity(),
				IConstants.SP_USER);
		su.setUserPictureUrl(uploadHeadModule.headurl);
		user_sp.setUserPictureUrl(uploadHeadModule.headurl);

		imageLoader.displayImage(user_sp.getUserPictureUrl(), head, options);

	}

	class SaveHeadImageAsy extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... params) {

			if (android.os.Environment.getExternalStorageState().equals(
					android.os.Environment.MEDIA_MOUNTED)) {
				File dirFile = new File(Environment
						.getExternalStorageDirectory().getAbsolutePath()
						+ "/GuangGuang/user/");
				if (!dirFile.exists()) {
					dirFile.mkdirs();
				}

				String headUrl = user_sp.getUserPictureUrl();

				try {
					Bitmap photo = BitmapFactory.decodeStream(new URL(headUrl)
							.openStream());
					CompressFormat format = Bitmap.CompressFormat.JPEG;
					int quality = 100;
					OutputStream stream = null;

					stream = new FileOutputStream(Environment
							.getExternalStorageDirectory().getAbsolutePath()
							+ "/GuangGuang/user/head.jpg");

					photo.compress(format, quality, stream);
				} catch (Exception e) {
					return null;
				}

			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
		}
	}
}
